/*
 * Copyright (c) 2009, David A. Freels Sr.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package net.whippetcode.plugins.intellij.hudson.parser;

import net.whippetcode.plugins.intellij.hudson.domain.test.TestClass;
import net.whippetcode.plugins.intellij.hudson.domain.test.TestMethod;
import net.whippetcode.plugins.intellij.hudson.domain.test.TestPackage;
import net.whippetcode.plugins.intellij.hudson.domain.test.TestStatus;
import net.whippetcode.plugins.intellij.hudson.util.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * This class handles parsing of test reports.
 *
 * @author David A. Freels Sr.
 */
public class TestHandler
{
	private static final String TEST_RESULT = "testResult";
	private static final String SUREFIRE_AGGREGATED_REPORT = "surefireAggregatedReport";
	private static final String FAIL_COUNT = "failCount";
	private static final String PASS_COUNT = "passCount";
	private static final String SKIP_COUNT = "skipCount";
	private static final String TOTAL_COUNT = "totalCount";
	private static final String CHILD = "child";
	private static final String NAME = "name";
	private static final String STATUS = "status";
	private static final String STATU = "statu";
	private static final String STDOUT = "stdout";
	private static final String STDERR = "stderr";
	private static final String ERROR_STACK_TRACE = "errorStackTrace";
	private static final String SUREFIRE_CHILD_REPORT = "childReport";
	private static final String SUREFIRE_RESULT = "result";
	private static final String SUREFIRE_PACKAGE_URL = "child/url";

	private List<TestPackage> tests = new ArrayList<TestPackage>();
	private String failCount = "0";
	private String passCount = "0";
	private String skipCount = "0";
	private String totalCount = "0";

	public TestHandler(URL url) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException
	{
		Document doc = XMLUtil.createDocument(url);
		Element element = doc.getDocumentElement();
		failCount = XMLUtil.getTextElement(FAIL_COUNT, element);
		skipCount = XMLUtil.getTextElement(SKIP_COUNT, element);
		if (TEST_RESULT.equals(element.getTagName()))
		{
			passCount = XMLUtil.getTextElement(PASS_COUNT, element);
			totalCount = generateTotalCount();

			//Parse the packages
			parsePackages(element, null);
		}
		else if (SUREFIRE_AGGREGATED_REPORT.equals(element.getTagName()))
		{
			totalCount = XMLUtil.getTextElement(TOTAL_COUNT, element);
			passCount = generatePassCount();

			NodeList packages = XMLUtil.getElements(SUREFIRE_CHILD_REPORT, element);

			Node report;
			for (int i = 0; i < packages.getLength(); i++)
			{
				report = packages.item(i);
				parsePackages(XMLUtil.getElement(SUREFIRE_RESULT, report), XMLUtil.getTextElement(SUREFIRE_PACKAGE_URL, report));
			}
		}
	}

	private String generatePassCount()
	{
		int pass = Integer.parseInt(totalCount);
		pass -= Integer.parseInt(failCount);
		pass -= Integer.parseInt(skipCount);
		return "" + pass;
	}

	private void parsePackages(Node element, String parseURL)
		 throws XPathExpressionException
	{
		NodeList packages = XMLUtil.getElements(CHILD, element);
		int childCount = packages.getLength();
		Node pkgNode;
		TestPackage pkg;
		for (int i = 0; i < childCount; i++)
		{
			pkgNode = packages.item(i);
			pkg = new TestPackage();
			pkg.setName(XMLUtil.getTextElement(NAME, pkgNode));
			pkg.setFailCount(XMLUtil.getTextElement(FAIL_COUNT, pkgNode));
			pkg.setPassCount(XMLUtil.getTextElement(PASS_COUNT, pkgNode));
			pkg.setSkipCount(XMLUtil.getTextElement(SKIP_COUNT, pkgNode));
			//This should only be set if each test method requires an additional query
			//to get the standard out and standard error. Maven projects require this.
			pkg.setBaseUrl(parseURL);

			parseClasses(pkgNode, pkg);
			tests.add(pkg);
		}
	}

	private void parseClasses(Node pkgNode, TestPackage pkg)
		 throws XPathExpressionException
	{
		Node clsNode;
		NodeList classes = XMLUtil.getElements(CHILD, pkgNode);
		int classCount = classes.getLength();
		for (int j = 0; j < classCount; j++)
		{
			clsNode = classes.item(j);
			TestClass clz = new TestClass();
			clz.setName(XMLUtil.getTextElement(NAME, clsNode));
			clz.setFailCount(XMLUtil.getTextElement(FAIL_COUNT, clsNode));
			clz.setPassCount(XMLUtil.getTextElement(PASS_COUNT, clsNode));
			clz.setSkipCount(XMLUtil.getTextElement(SKIP_COUNT, clsNode));

			parseMethods(clsNode, clz);
			pkg.addTestClass(clz);
		}
	}

	private void parseMethods(Node clsNode, TestClass clz)
		 throws XPathExpressionException
	{
		Node mtdNode;
		NodeList methods = XMLUtil.getElements(CHILD, clsNode);
		int methodCount = methods.getLength();
		for (int k = 0; k < methodCount; k++)
		{
			mtdNode = methods.item(k);
			TestMethod method = new TestMethod();
			method.setName(XMLUtil.getTextElement(NAME, mtdNode));

			if (XMLUtil.hasContent(STATU, mtdNode))
			{
				getStatus(STATU, mtdNode, method);
			}
			else if (XMLUtil.hasContent(STATUS, mtdNode))
			{
				getStatus(STATUS, mtdNode, method);
			}

			if (XMLUtil.hasContent(ERROR_STACK_TRACE, mtdNode))
			{
				method.setStandardError(XMLUtil.getTextElement(ERROR_STACK_TRACE, mtdNode));
			}
			else if (XMLUtil.hasContent(STDERR, mtdNode))
			{
				method.setStandardError(XMLUtil.getTextElement(STDERR, mtdNode));
			}
			method.setStandardOutput(XMLUtil.getTextElement(STDOUT, mtdNode));

			clz.addTestMethod(method);
		}
	}

	private void getStatus(String expression, Node mtdNode, TestMethod method)
		 throws XPathExpressionException
	{
		String status;
		status = XMLUtil.getTextElement(expression, mtdNode);
		if (status != null && status.trim().length() > 0)
		{
			method.setStatus(TestStatus.valueOf(status));
		}
	}

	private String generateTotalCount()
	{
		int total = Integer.parseInt(failCount);
		total += Integer.parseInt(passCount);
		total += Integer.parseInt(skipCount);
		return "" + total;
	}

	public String getFailCount()
	{
		return failCount;
	}

	public String getPassCount()
	{
		return passCount;
	}

	public String getSkipCount()
	{
		return skipCount;
	}

	public String getTotalCount()
	{
		return totalCount;
	}

	public List<TestPackage> getPackages()
	{
		return tests;
	}
}
